<!-- 视频播放器 webrtc -->
<template>
	<div>
		<div>{{ props.viewType }}</div>
		<video :id="'videoPlayer' + props.deviceCode" autoplay controls></video>
	</div>
</template>

<script lang="ts" setup name="video-webrtc">
import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import { JSWebrtc } from './jswebrtc.min.js';
import { getUrl } from '/@/utils/hm';
import { smokeStore } from '/@/stores/smoke';
import { useUserInfo } from '/@/stores/userInfo';

const props = defineProps({
	deviceCode: {
		type: String,
		default: '',
	},
	viewType: {
		type: String,
		default: 'live',
	},
});

// const videoEl = ref(null);

onMounted(() => {
	// initVideo();
});

onUnmounted(() => {
	// TODO: 销户视频时，关闭视频流等操作
});

nextTick(() => {
	initVideo();
});

function initVideo() {
	if (props.viewType == 'live') {
		console.log('直播准备');
	}

	if (props.viewType == 'review') {
		console.log('回看准备');
	}

	let dom = document.getElementById(`videoPlayer${props.deviceCode}`);
	// let dom = videoEl.value;
	let url = getVideoUrl();
	console.log(url);

	new JSWebrtc.Player(
		// `webrtc://webrtc.20180807.com:1990/live/${this.iccid}`,
		// `webrtc://test.20180807.com:1990/live/${this.iccid}`,
		// `webrtc://app.20180807.com:1990/live/${props.iccid}`,
		'webrtc://47.99.69.23/live/M014002112208001351',
		{
			video: dom,
			autoplay: true,
			onPlay: () => {
				console.log('start play');
			},
		}
	);
}

// 查看视频
let continueTimer: any = null;
let wsConn = smokeStore().wsConn;
async function getVideo() {
	let params = {
		cmdType: 'getVideo',
		deviceCode: props.deviceCode,
		data: null,
	};
	wsConn.send(JSON.stringify(params));

	clearInterval(continueTimer);
	continueTimer = setInterval(() => {
		continueDevice();
	}, 15000);
}

function closeVideo() {
	let wsConn = smokeStore().wsConn;
	let params = {
		cmdType: 'closeVideo',
		deviceCode: props.deviceCode,
		data: null,
	};
	wsConn.send(JSON.stringify(params));
}

// 视频续时
function continueDevice() {
	let params = {
		cmdType: 'getVideo',
		deviceCode: props.deviceCode,
		data: null,
	};
	wsConn.send(JSON.stringify(params));
}

// 获取RTMP播放地址
function getVideoUrl() {
	let webrtcUrl = getUrl('webrtcUrl');
	let uid = useUserInfo().userInfos.id;

	let url = '';
	if (props.viewType == 'live') {
		url = `${webrtcUrl}/live/${props.deviceCode}`;
	}

	if (props.viewType == 'review') {
		url = `${webrtcUrl}/review/${uid}/${props.deviceCode}`;
	}

	return url;
}
</script>

<style lang="scss" scoped>
video {
	width: 100%;
	aspect-ratio: 16/9;
	background-color: #333333;
}
</style>
